package com.ruoyi.standingbook.evaluate.service.impl;

import java.text.NumberFormat;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.api.dto.evaluate.EnvironmentDeductMarksDto;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.standingbook.evaluate.domain.Evaluate;
import com.ruoyi.standingbook.evaluate.domain.bo.EvaluateBo;
import com.ruoyi.standingbook.evaluate.domain.vo.EvaluateImportDetailVo;
import com.ruoyi.standingbook.evaluate.domain.vo.EvaluateVo;
import com.ruoyi.standingbook.evaluate.mapper.EvaluateMapper;
import com.ruoyi.standingbook.evaluate.service.IEvaluateService;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;

/**
 * 市环境测评Service业务层处理
 *
 * @author cc
 * @date 2023-04-27
 */
@RequiredArgsConstructor
@Service
public class EvaluateServiceImpl implements IEvaluateService {

    private final EvaluateMapper baseMapper;

    /**
     * 查询市环境测评
     */
    @Override
    public EvaluateVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询市环境测评列表
     */
    @Override
    public TableDataInfo<EvaluateVo> queryPageList(EvaluateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Evaluate> lqw = buildQueryWrapper(bo);
        Page<EvaluateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询市环境测评列表
     */
    @Override
    public List<EvaluateVo> queryList(EvaluateBo bo) {
        LambdaQueryWrapper<Evaluate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Evaluate> buildQueryWrapper(EvaluateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Evaluate> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getItemName()), Evaluate::getItemName, bo.getItemName());
        lqw.like(StringUtils.isNotBlank(bo.getEvaluateLocaltion()), Evaluate::getEvaluateLocaltion, bo.getEvaluateLocaltion());
        lqw.eq(bo.getServiceTypeId() != null, Evaluate::getServiceTypeId, bo.getServiceTypeId());
        lqw.between(params.get("beginEvaluateTime") != null && params.get("endEvaluateTime") != null,
            Evaluate::getEvaluateTime ,params.get("beginEvaluateTime"), params.get("endEvaluateTime"));
        lqw.between(params.get("beginPublishDate") != null && params.get("endPublishDate") != null,
            Evaluate::getPublishDate ,params.get("beginPublishDate"), params.get("endPublishDate"));
        return lqw;
    }

    /**
     * 新增市环境测评
     */
    @Override
    public Boolean insertByBo(EvaluateBo bo) {
        Evaluate add = BeanUtil.toBean(bo, Evaluate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改市环境测评
     */
    @Override
    public Boolean updateByBo(EvaluateBo bo) {
        Evaluate update = BeanUtil.toBean(bo, Evaluate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Evaluate entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除市环境测评
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

	@Override
	public Boolean batchInsert(List<EvaluateImportDetailVo> voList) {

		List<Evaluate> list = BeanCopyUtils.copyList(voList, Evaluate.class);
		list.forEach(e -> {
			e.setId(null);
			e.restBase();
		});
		return this.baseMapper.insertBatch(list);
	}

    /**
     * 扣分最多的5条
     * @param date 当天
     * @return 扣分最多的5条
     */
	@Override
	public List<EnvironmentDeductMarksDto> getEnvironmentDeductMarksDtoList(String date) {
		QueryWrapper<Evaluate> qw = new QueryWrapper<>();
		qw.ge(!StringUtils.isEmpty(date), "publish_date", date);
        qw.eq(true,"del_flag","0");
		return this.baseMapper.getEnvironmentDeductMarksDtoList(qw);
	}


    @Override
    public String getAvgScoreMonth(Evaluate evaluate){
        List<Evaluate> list  =  this.baseMapper.getAvgScoreMonth(evaluate);
        return getAvgScore(list);
    }

    @Override
    public String getAvgScoreYear(Evaluate evaluate){
        List<Evaluate> list  =  this.baseMapper.getAvgScoreYear(evaluate);
        return getAvgScore(list);
    }

    private String getAvgScore(List<Evaluate> list){
        float score = 0;
        float sum = 0;
        float weight=0;
        for(Evaluate item:list){
            sum+=item.getEvaluateScore().floatValue()*item.getWeight();
            weight+=item.getWeight();
        }
        if(weight==0)weight=1;
        score = sum/weight;
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        return format.format(score);
    }
}
